package xyz.redtorch.client.strategy.suit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import xyz.redtorch.client.strategy.StrategyTemplate;
import xyz.redtorch.common.util.UUIDStringPoolUtils;
import xyz.redtorch.pb.CoreEnum.DirectionEnum;
import xyz.redtorch.pb.CoreEnum.OffsetFlagEnum;
import xyz.redtorch.pb.CoreEnum.OrderPriceTypeEnum;
import xyz.redtorch.pb.CoreEnum.OrderStatusEnum;
import xyz.redtorch.pb.CoreField.OrderField;
import xyz.redtorch.pb.CoreField.TickField;
import xyz.redtorch.pb.CoreField.TradeField;

/**
 * @author Skywalker
 *
 */
public class StrategyDemo extends StrategyTemplate {

	private static final Logger logger = LoggerFactory.getLogger(StrategyDemo.class);

	private int tickCount = 0;
//	private String preOrderId = null;
//	private String preOriginOrderId = null;
	private int priceTick = 1;

	public StrategyDemo(String strategyId) {
		super(strategyId);
	}

	@Override
	public void onInit() {
		super.onInit();
		subscribe("m2009@DCE@FUTURES", null);
	}

	@Override
	public void onTick(TickField tick) {
		logger.info("收到Tick, UnifiedSymbol: {}, GatewayId {}", tick.getUnifiedSymbol(), tick.getGatewayId());

		tickCount++;

		if (tickCount % 5 == 0) {
//			submitOrder("m2009@DCE@FUTURES", OrderPriceTypeEnum.OPT_LimitPrice, DirectionEnum.D_Buy,
//					OffsetFlagEnum.OF_Open, "079491@CNY@9df0fa80-7ec9-462e-97ed-04ccccc35e2e",
//					tick.getAskPrice(0) + priceTick, 1, null, false);
//			submitOrder("m2009@DCE@FUTURES", OrderPriceTypeEnum.OPT_LimitPrice, DirectionEnum.D_Sell,
//					OffsetFlagEnum.OF_Open, "079491@CNY@9df0fa80-7ec9-462e-97ed-04ccccc35e2e",
//					tick.getBidPrice(0) - priceTick, 1, null, false);
		}
	}

	@Override
	public void onTrade(TradeField trade) {
		// 校验是否是策略发出的定单
		if (originOrderIdSet.contains(trade.getOriginOrderId())) {
			logger.info("策略{}收到成交信息 \n {}", strategyId, trade);
		}
	}

	@Override
	public void onOrder(OrderField order) {
		if (originOrderIdSet.contains(order.getOriginOrderId())) {
			logger.warn("策略{}收到委托信息准备撤单 \n {}", strategyId, order);
			if (OrderStatusEnum.OS_NoTradeQueueing.equals(order.getOrderStatus())
					|| OrderStatusEnum.OS_NoTradeNotQueueing.equals(order.getOrderStatus())
					|| OrderStatusEnum.OS_PartTradedQueueing.equals(order.getOrderStatus())
					|| OrderStatusEnum.OS_PartTradedNotQueueing.equals(order.getOrderStatus())
					|| OrderStatusEnum.OS_NotTouched.equals(order.getOrderStatus())) {
			boolean cancelOrder = cancelOrder(order.getOrderId(), order.getOriginOrderId(), UUIDStringPoolUtils.getUUIDString(), false);
			if (cancelOrder) {
				originOrderIdSet.remove(order.getOriginOrderId());
			}
//			logger.warn("策略{}撤单成功 {}", strategyId, cancelOrder);
			}
		}

	}
}
